package com.ruoyi.tjfx.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.report_hntjg.domain.ReportHntjgGjbhcjlbBaDetail;
import com.ruoyi.report_hntjg.domain.ReportHntjgGjbhcjlbBsInfo;
import com.ruoyi.report_hntjg.domain.vo.ReportHntjgGjbhcjlbBaDetailVo;
import com.ruoyi.report_hntjg.domain.vo.ReportHntjgGjbhcjlbBsInfoVo;
import com.ruoyi.report_hntjg.mapper.ReportHntjgGjbhcjlbBaDetailMapper;
import com.ruoyi.report_hntjg.mapper.ReportHntjgGjbhcjlbBsInfoMapper;
import com.ruoyi.report_ljlm.domain.YsdgsfjlbBsDetail;
import com.ruoyi.report_ljlm.domain.YsdgsfjlbBsInfo;
import com.ruoyi.report_ljlm.domain.vo.YsdgsfjlbBsDetailVo;
import com.ruoyi.report_ljlm.domain.vo.YsdgsfjlbBsInfoVo;
import com.ruoyi.report_ljlm.mapper.YsdgsfjlbBsDetailMapper;
import com.ruoyi.report_ljlm.mapper.YsdgsfjlbBsInfoMapper;
import com.ruoyi.syrw.domain.BiExcelType;
import com.ruoyi.syrw.domain.RefReportExcel;
import com.ruoyi.syrw.domain.bo.BsDataReportBo;
import com.ruoyi.syrw.domain.bo.TaiZhangQueryBo;
import com.ruoyi.syrw.domain.vo.BsDataReportVo;
import com.ruoyi.syrw.domain.vo.RefReportExcelVo;
import com.ruoyi.syrw.mapper.BiExcelTypeMapper;
import com.ruoyi.syrw.mapper.BsDataReportMapper;
import com.ruoyi.syrw.mapper.RefReportExcelMapper;
import com.ruoyi.syrw.service.IBsDataReportService;
import com.ruoyi.tjfx.domain.*;
import com.ruoyi.tjfx.service.ReportTJFXService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 特色统计
 *
 * @author zyb
 * @date 2024-12-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/tstj")
public class TeSeTJController {

    private final ReportTJFXService reportTJFXService;
    private final IBsDataReportService iBsDataReportService;
    private final RefReportExcelMapper refReportExcelMapper;
    private final BiExcelTypeMapper biExcelTypeMapper;
    private final YsdgsfjlbBsInfoMapper ysdgsfjlbBsInfoMapper;
    private final YsdgsfjlbBsDetailMapper ysdgsfjlbBsDetailMapper;
    private final ReportHntjgGjbhcjlbBsInfoMapper hntjgGjbhcjlbBsInfoMapper;
    private final ReportHntjgGjbhcjlbBaDetailMapper hntjgGjbhcjlbBaDetailMapper;


//    /**
//     * 根据syTypeId和deptId查询试验任务台账
//     */
//    @SaCheckLogin
//    @GetMapping("/taiZhang")
//    public TableDataInfo taiZhang(@Validated(QueryGroup.class)TaiZhangQueryBo bo, PageQuery pageQuery) {
//        return reportTJFXService.taiZhang(bo, pageQuery);
//    }
//
//    /**
//     *  根据syTypeId和deptId导出试验台账
//     */
//    @SaCheckLogin
//    @PostMapping("/exportTz")
//    public void exportBhgtz(@Validated(QueryGroup.class)TaiZhangQueryBo bo , HttpServletResponse response) {
//        TableDataInfo tableDataInfo = reportTJFXService.taiZhang(bo, new PageQuery());
//        Map<String, String> map = new HashMap<>();
//        // 台账
//        List rows = tableDataInfo.getRows();
//        String tamplatePath = getTzTemplatePath(bo);
//        ExcelUtil.exportTemplate(CollUtil.newArrayList(map, rows), "试验台账.xlsx", tamplatePath, response);
//    }
//
//    private String getTzTemplatePath(TaiZhangQueryBo bo) {
//        if (bo.getSyType() == 2L) {
//            return "excel/土工试验台账.xlsx";
//        } else if (bo.getSyType() == 4L) {
//            return "excel/粗集料试验台账.xlsx";
//        } else if (bo.getSyType() == 5L) {
//            return "excel/细集料试验台账.xlsx";
//        } //  钢筋原材试验 复制粗集料修改 lb
//        else if (25L == bo.getSyType()) {
//            return "excel/钢筋原材试验台账.xlsx";
//        }
//        //  钢筋焊接试验 复制粗集料修改 lb
//        else if (136L == bo.getSyType()) {
//            return "excel/钢筋焊接试验台账.xlsx";
//        }
//        // 钢筋机械连接试验 复制粗集料修改 lb
//        else if (137L == bo.getSyType()) {
//            return "excel/钢筋机械连接验台账.xlsx";
//        }
//        // 粉煤灰试验（掺合料） 复制粗集料修改 zyb
//        else if (22L == bo.getSyType()) {
//            return "excel/粉煤灰试验（掺合料）试验台账.xlsx";
//        }
//        //  水泥 lb
//        else if (10L == bo.getSyType()) {
//            return "excel/水泥试验台账.xlsx";
//        }
//        //  水泥混凝土配合比  xs
//        else if (14L == bo.getSyType()) {
//            return "excel/水泥混凝土配合比试验台账.xlsx";
//        }
//        //  水泥砂浆配合比试验  xs
//        else if (17L == bo.getSyType()) {
//            return "excel/水泥砂浆配合比试验台账.xlsx";
//        }
//        // 沥青混合料配合比  lb
//        else if (139L == bo.getSyType()) {
//            return "excel/沥青混合料配合比试验台账.xlsx";
//        }
//        // 基坑、地基与桩基试验  zyb
//        else if (31L == bo.getSyType()) {
//            return "excel/基坑、地基与桩基试验台账.xlsx";
//        }
//        // 压浆材料 lb
//        else if (69L == bo.getSyType()) {
//            return "excel/压浆材料试验台账.xlsx";
//        }
//        // 路基路面回弹弯沉试验 lb
//        else if (135L == bo.getSyType()) {
//            return "excel/路基路面试验台账.xlsx";
//        }
//        return "excel/未知试验类型台账.xlsx";
//    }
//
//    /**
//     * 不合格台账
//     */
//    @SaCheckLogin
//    @GetMapping("/bhgtz")
//    public TableDataInfo bhgtz(BsDataReportBo bo, PageQuery pageQuery) {
//        return reportTJFXService.bhgtz(bo, pageQuery);
//    }
//
//

    /**
     * 试验标记保存
     */
    @SaCheckLogin
    @PostMapping("/saveSybj")
    public R saveSybj(@RequestBody Map<String, Object> params) {
        Assert.notNull(params.get("reportId"), "reportId不能为空");
        Assert.notNull(params.get("syType"), "syType不能为空");
        if (131 == (Integer) params.get("syType")) {
            // 路基路面压实度试验
            LjlmysdSybjBo ljlmysdSybjBo = new LjlmysdSybjBo();
            BeanUtil.fillBeanWithMapIgnoreCase(params, ljlmysdSybjBo, true);
            List<RefReportExcelVo> refReportExcelVos = refReportExcelMapper.selectVoList(new LambdaQueryWrapper<RefReportExcel>()
                .eq(RefReportExcel::getReportId, ljlmysdSybjBo.getReportId())
                .eq(RefReportExcel::getExcelTypeId, 1829048815838072834L));
            if (CollUtil.isEmpty(refReportExcelVos)) {
                return R.fail("标记失败，该试验任务下没有路基路面压实度试验检测记录表(灌砂法)");
            }
            refReportExcelVos.forEach(v -> {
                ysdgsfjlbBsInfoMapper.update(null, new LambdaUpdateWrapper<YsdgsfjlbBsInfo>()
                    .set(YsdgsfjlbBsInfo::getZhuangh, ljlmysdSybjBo.getZhuangh())
                    .set(YsdgsfjlbBsInfo::getCengw, ljlmysdSybjBo.getCengw())
                    .set(YsdgsfjlbBsInfo::getJiegwmc, ljlmysdSybjBo.getJiegwmc())
                    .eq(YsdgsfjlbBsInfo::getExcelId, v.getExcelId()));
            });
            return R.ok();
        } else if (30 == (Integer) params.get("syType")) {
            // 混凝土结构试验 syTypeId=30
            HntjgsySybjBo bo = new HntjgsySybjBo();
            BeanUtil.fillBeanWithMapIgnoreCase(params, bo, true);
            List<RefReportExcelVo> refReportExcelVos = refReportExcelMapper.selectVoList(new LambdaQueryWrapper<RefReportExcel>()
                .eq(RefReportExcel::getReportId, bo.getReportId())
                .eq(RefReportExcel::getExcelTypeId, 1821065235280064513L));
            if (CollUtil.isEmpty(refReportExcelVos)) {
                return R.fail("标记失败，该试验任务下没有钢筋位置及保护层厚度试验检测记录表");
            }
            refReportExcelVos.forEach(v -> {
                hntjgGjbhcjlbBsInfoMapper.update(null, new LambdaUpdateWrapper<ReportHntjgGjbhcjlbBsInfo>()
                    .set(ReportHntjgGjbhcjlbBsInfo::getDunztsh, bo.getDunztsh())
                    .set(ReportHntjgGjbhcjlbBsInfo::getCedqdwz, bo.getCedqdwz())
                    .eq(ReportHntjgGjbhcjlbBsInfo::getExcelId, v.getExcelId()));
            });
            return R.ok();
        } else {
            throw new ServiceException("该试验类型暂不支持试验标记");
        }
    }

    /**
     * 获取试验标记
     *
     * @param reportId 主键
     */
    @SaCheckLogin
    @GetMapping("/sybj/{reportId}")
    public R<Map<String, Object>> getSybjInfo(@NotNull(message = "主键不能为空")
                                              @PathVariable Long reportId) {
        HashMap<String, Object> resultMap = new HashMap<>();
        BsDataReportVo reportVo = iBsDataReportService.queryById(reportId);
        if (131 == reportVo.getSyType()) {
            // 路基路面压实度试验 syTYpeId=131
            if (CollUtil.isNotEmpty(reportVo.getExcelTypeList())) {
                for (RefReportExcelVo refReportExcelVo : reportVo.getExcelTypeList()) {
                    if (1829048815838072834L == refReportExcelVo.getExcelTypeId()) {
                        YsdgsfjlbBsInfoVo vo = ysdgsfjlbBsInfoMapper.selectVoById(refReportExcelVo.getExcelId());
                        resultMap.put("zhuangh", vo.getZhuangh());
                        resultMap.put("cengw", vo.getCengw());
                        resultMap.put("jiegwmc", vo.getJiegwmc());
                        break;
                    }
                }
            }
        }
        if (30 == reportVo.getSyType()) {
            //  混凝土结构试验 syTypeId=30：
            if (CollUtil.isNotEmpty(reportVo.getExcelTypeList())) {
                for (RefReportExcelVo refReportExcelVo : reportVo.getExcelTypeList()) {
                    if (1821065235280064513L == refReportExcelVo.getExcelTypeId()) {
                        ReportHntjgGjbhcjlbBsInfoVo vo = hntjgGjbhcjlbBsInfoMapper.selectVoById(refReportExcelVo.getExcelId());
                        resultMap.put("dunztsh", vo.getDunztsh());
                        resultMap.put("cedqdwz", vo.getCedqdwz());
                        break;
                    }
                }
            }
        }
        return R.ok(resultMap);
    }

    /**
     * 获取xx试验类型下的 试验的 工程部位列表
     */
    @SaCheckLogin
    @GetMapping("/gcbwList")
    public R<List<String>> gcbwList(@Validated(QueryGroup.class) GcbwQueryBo bo) {
        if (131 == bo.getSyTypeId()) {
            // 路基路面压实度试验 syTYpeId=131
            return R.ok(ysdgsfjlbBsInfoMapper.selectGcbwList(bo.getDeptId(), bo.getSyTypeId()));
        }
        if (30 == bo.getSyTypeId()) {
            //  混凝土结构试验 syTypeId=30：
            return R.ok(hntjgGjbhcjlbBsInfoMapper.selectGcbwList(bo.getDeptId(), bo.getSyTypeId()));
        }
        throw new ServiceException("获取工程部位列表失败");
    }

    /**
     * 特色统计 只统计有试验标记（桩号）的记录
     */
    @SaCheckLogin
    @GetMapping("/tstjList")
    public R tstjList(@Validated(QueryGroup.class) GcbwQueryBo bo) {
//        List<Map<String, Object> > list = refReportExcelMapper.tstjList(bo.getDeptId(), bo.getSyTypeId(), bo.getGongcbwyt());
        if (StrUtil.isEmpty(bo.getGongcbwyt())) {
            throw new ServiceException("工程部位不能为空");
        }
        if (131 == bo.getSyTypeId()) {
            // 路基路面压实度试验 syTYpeId=131
            List<YsdgsfjlbBsInfoVo> list = ysdgsfjlbBsInfoMapper.tstjList(bo.getDeptId(), bo.getGongcbwyt());
            list.forEach(v -> {
                List<YsdgsfjlbBsDetailVo> detailList = ysdgsfjlbBsDetailMapper.selectVoList(
                    new LambdaQueryWrapper<YsdgsfjlbBsDetail>().eq(YsdgsfjlbBsDetail::getExcelId, v.getExcelId()));
                StringBuilder cedwzStr = new StringBuilder("");
                StringBuilder shiczStr = new StringBuilder("");
                if (CollUtil.isNotEmpty(detailList)) {
//                    v.setDetailList(detailList);
                    for (YsdgsfjlbBsDetailVo detailVo : detailList) {
                        if (BigDecimalUtil.isNotEmpty(detailVo.getYasd()) && StrUtil.isNotEmpty(detailVo.getQvyzhwz())) {
                            cedwzStr.append(detailVo.getQvyzhwz());
                            shiczStr.append(detailVo.getYasd());
                        }
                    }
                }
                v.setCedwzStr(cedwzStr.toString());
                v.setShiczStr(cedwzStr.toString());
            });
            return R.ok(list);
        }
        if (30 == bo.getSyTypeId()) {
            //  混凝土结构试验 syTypeId=30：
            List<ReportHntjgGjbhcjlbBsInfoVo> list = hntjgGjbhcjlbBsInfoMapper.tstjList(bo.getDeptId(), bo.getGongcbwyt());
            list.forEach(v -> {
                // 查询detail
                List<ReportHntjgGjbhcjlbBaDetailVo> baDetailVos = hntjgGjbhcjlbBaDetailMapper.selectVoList(new LambdaQueryWrapper<ReportHntjgGjbhcjlbBaDetail>()
                    .eq(ReportHntjgGjbhcjlbBaDetail::getExcelId, v.getExcelId())
                    .orderByAsc(ReportHntjgGjbhcjlbBaDetail::getSort));
                if (CollUtil.isNotEmpty(baDetailVos) || BigDecimalUtil.isEmpty(v.getBaohcSjz())) {
                    // 有效详细列表
                    List<ReportHntjgGjbhcjlbBaDetailVo> yxDetailVos = baDetailVos.subList(0,40)
                        .stream()
                        .filter(baDetailVo -> ObjUtil.isNotNull(baDetailVo.getShiczPjz())).collect(Collectors.toList());
                    if (CollUtil.isEmpty(yxDetailVos)) {
                        return;
                    }
                    StringBuilder cedDetailStrBuilder = new StringBuilder("");
                    double[] hegeNum = {0};
                    IntStream.range(0, yxDetailVos.size()).forEach(i -> {
                        cedDetailStrBuilder.append("测点").append(i+1).append(":").append(yxDetailVos.get(i).getShiczPjz()).append(";");
                        if (yxDetailVos.get(i).getShiczPjz() >= (v.getBaohcSjz().doubleValue())) {
                            hegeNum[0]++;
                        }
                    });
                    v.setHegl(String.format("%.2f", (hegeNum[0] * 100 / yxDetailVos.size())));
                    v.setCedDetailStr(cedDetailStrBuilder.toString());
//                    v.setBaohcList(baDetailVos.subList(0, 40));
                    double average = yxDetailVos
                        .stream()
                        .mapToDouble(ReportHntjgGjbhcjlbBaDetailVo::getShiczPjz)
                        .average().orElse(-1);
                    double max = yxDetailVos
                        .stream()
                        .mapToDouble(ReportHntjgGjbhcjlbBaDetailVo::getShiczPjz)
                        .max().orElse(-1);
                    double min = yxDetailVos
                        .stream()
                        .mapToDouble(ReportHntjgGjbhcjlbBaDetailVo::getShiczPjz)
                        .min().orElse(-1);

                    v.setCesbhcjz(-1 == average ? null : average);
                    v.setCesbhcMax(-1 == max ? null : max);
                    v.setCesbhcMin(-1 == min ? null : min);
                }
            });
            // 雷达图 begin
            SeriesDataVo data1 = new SeriesDataVo();
            data1.setName("设计保护层厚度");
            data1.setValue(list.stream()
                .filter(v -> BigDecimalUtil.isNotEmpty(v.getBaohcSjz()) && ObjUtil.isNotNull(v.getCesbhcjz()))
                .map(v -> v.getBaohcSjz().doubleValue())
                .collect(Collectors.toList()));
            SeriesDataVo data2 = new SeriesDataVo();
            data2.setName("实测保护层厚度");
            data2.setValue(list.stream()
                .filter(v -> BigDecimalUtil.isNotEmpty(v.getBaohcSjz()) && ObjUtil.isNotNull(v.getCesbhcjz()))
                .map(ReportHntjgGjbhcjlbBsInfoVo::getCesbhcjz)
                .collect(Collectors.toList()));
            List<SeriesDataVo> seriesDataVos = new ArrayList<>();
            seriesDataVos.add(data1);
            seriesDataVos.add(data2);
            // 雷达图 end
            int hegNum = 0;
            for (ReportHntjgGjbhcjlbBsInfoVo vo : list) {
                if ("100.00".equals(vo.getHegl()) || vo.getHegl() == null) {
                    hegNum++;
                }
            }
            HntjgTstjVo hntjgTstjVo = new HntjgTstjVo();
            hntjgTstjVo.setList(list);
            hntjgTstjVo.setSeriesDataVos(seriesDataVos);
            hntjgTstjVo.setHegNum(hegNum);
            hntjgTstjVo.setBuhegNum(list.size() - hegNum);
            return R.ok(hntjgTstjVo);
        }
        throw new ServiceException("获取工程部位列表失败");
    }
}
